using Microsoft.AspNetCore.Mvc;
using MVCWeekOne.Models;
using System.Text;
using System.Text.Json;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;

namespace MVCWeekOne.Controllers
{
    public class DefectiveController : Controller
    {
        private readonly IConfiguration _configuration;
        private readonly HttpClient _httpClient;
        private readonly string _readApiUrl;

        public DefectiveController(IConfiguration configuration, HttpClient httpClient)
        {
            _configuration = configuration;
            _httpClient = httpClient;
            _readApiUrl = _configuration["ApiSettings:ReadApiUrl"] ?? "http://localhost:5089/api";
        }

        /// <summary>
        /// 不良品管理页面
        /// </summary>
        public IActionResult Index()
        {
            // 传递API配置到视图
            ViewData["WriteApiUrl"] = _configuration["ApiSettings:WriteApiUrl"] ?? "http://localhost:5090/api";
            return View();
        }

        /// <summary>
        /// 获取不良品分页数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetPage(string? defectiveCode, string? defectiveName, int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                // 调用真实API
                var queryParams = new List<string>();
                if (!string.IsNullOrEmpty(defectiveCode))
                    queryParams.Add($"DefectiveCode={Uri.EscapeDataString(defectiveCode)}");
                if (!string.IsNullOrEmpty(defectiveName))
                    queryParams.Add($"DefectiveName={Uri.EscapeDataString(defectiveName)}");
                
                queryParams.Add($"Index={pageIndex}");
                queryParams.Add($"Size={pageSize}");

                var queryString = string.Join("&", queryParams);
                var url = $"{_readApiUrl}/Defective/GetPage?{queryString}";

                var response = await _httpClient.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    return Content(responseContent, "application/json");
                }
                else
                {
                    var errorMessage = response.StatusCode == System.Net.HttpStatusCode.Unauthorized 
                        ? "API需要认证，请先登录" 
                        : $"获取数据失败，状态码: {response.StatusCode}";
                    return Json(new { code = (int)response.StatusCode, msg = errorMessage, data = new List<object>() });
                }


            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取数据异常: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取不良品高级查询分页数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetAdvancedPage([FromQuery] DefectiveAdvancedQueryModel query)
        {
            try
            {
                // 调用真实API
                var queryParams = new List<string>();
                if (!string.IsNullOrEmpty(query.DefectiveCode))
                    queryParams.Add($"DefectiveCode={Uri.EscapeDataString(query.DefectiveCode)}");
                if (!string.IsNullOrEmpty(query.DefectiveName))
                    queryParams.Add($"DefectiveName={Uri.EscapeDataString(query.DefectiveName)}");
                
                queryParams.Add($"Index={query.PageIndex}");
                queryParams.Add($"Size={query.PageSize}");

                var queryString = string.Join("&", queryParams);
                var url = $"{_readApiUrl}/Defective/GetPage?{queryString}";

                var response = await _httpClient.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    return Content(responseContent, "application/json");
                }
                else
                {
                    var errorMessage = response.StatusCode == System.Net.HttpStatusCode.Unauthorized 
                        ? "API需要认证，请先登录" 
                        : $"获取数据失败，状态码: {response.StatusCode}";
                    return Json(new { code = (int)response.StatusCode, msg = errorMessage, data = new List<object>() });
                }


            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取数据异常: {ex.Message}" });
            }
        }







        /// <summary>
        /// 新增不良品
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Add(IFormFile? attachmentFile, IFormFile? imageFile, string defectiveCode, string defectiveName, string? attachmentPath = null, string? imagePath = null)
        {
            try
            {
                // 验证请求参数
                if (string.IsNullOrWhiteSpace(defectiveCode))
                {
                    return Json(new { code = 400, msg = "不良品项编号不能为空", data = 0 });
                }

                if (string.IsNullOrWhiteSpace(defectiveName))
                {
                    return Json(new { code = 400, msg = "不良品项名称不能为空", data = 0 });
                }

                // 获取当前登录用户ID（这里需要根据实际的认证系统来实现）
                var creatorId = GetCurrentUserId();
                if (creatorId <= 0)
                {
                    return Json(new { code = 401, msg = "用户未登录或登录已过期", data = 0 });
                }

                // 处理文件上传
                string? finalAttachmentPath = attachmentPath;
                string? finalImagePath = imagePath;

                if (string.IsNullOrWhiteSpace(finalAttachmentPath) && attachmentFile != null && attachmentFile.Length > 0)
                {
                    finalAttachmentPath = await SaveFile(attachmentFile, "attachments");
                }

                if (string.IsNullOrWhiteSpace(finalImagePath) && imageFile != null && imageFile.Length > 0)
                {
                    finalImagePath = await SaveFile(imageFile, "images");
                }

                // 获取WriteApiUrl配置
                var writeApiUrl = _configuration["ApiSettings:WriteApiUrl"] ?? "http://localhost:5090/api";
                var url = $"{writeApiUrl}/Defective/Add";

                // 构建请求数据
                var requestData = new
                {
                    defectiveCode = defectiveCode,
                    defectiveName = defectiveName,
                    attachmentPath = finalAttachmentPath ?? "",
                    imagePath = finalImagePath ?? "",
                    creatorId = creatorId
                };

                // 发送POST请求到WriteApiUrl
                var jsonContent = JsonSerializer.Serialize(requestData);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var result = JsonSerializer.Deserialize<AddDefectiveResponse>(responseContent, new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });

                    return Json(result);
                }
                else
                {
                    var errorMessage = response.StatusCode == System.Net.HttpStatusCode.Unauthorized 
                        ? "API需要认证，请先登录" 
                        : $"新增失败，状态码: {response.StatusCode}";
                    return Json(new { code = (int)response.StatusCode, msg = errorMessage, data = 0 });
                }
            }
            catch (Exception ex)
            {
                return Json(new { code = 500, msg = $"新增异常: {ex.Message}", data = 0 });
            }
        }

        /// <summary>
        /// 更新不良品
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Update(IFormFile? attachmentFile, IFormFile? imageFile, string id, string defectiveCode, string defectiveName, string? attachmentPath = null, string? imagePath = null)
        {
            try
            {
                // 验证请求参数
                if (string.IsNullOrWhiteSpace(id) || !int.TryParse(id, out int defectiveId))
                {
                    return Json(new { code = 400, msg = "无效的不良品项ID", data = 0 });
                }

                if (string.IsNullOrWhiteSpace(defectiveCode))
                {
                    return Json(new { code = 400, msg = "不良品项编号不能为空", data = 0 });
                }

                if (string.IsNullOrWhiteSpace(defectiveName))
                {
                    return Json(new { code = 400, msg = "不良品项名称不能为空", data = 0 });
                }

                // 获取当前登录用户ID（这里需要根据实际的认证系统来实现）
                var modifierId = GetCurrentUserId();
                if (modifierId <= 0)
                {
                    return Json(new { code = 401, msg = "用户未登录或登录已过期", data = 0 });
                }

                // 处理文件上传（若前端已上传并传来路径则直接使用）
                string? finalAttachmentPath = attachmentPath;
                string? finalImagePath = imagePath;

                if (string.IsNullOrWhiteSpace(finalAttachmentPath) && attachmentFile != null && attachmentFile.Length > 0)
                {
                    finalAttachmentPath = await SaveFile(attachmentFile, "attachments");
                }

                if (string.IsNullOrWhiteSpace(finalImagePath) && imageFile != null && imageFile.Length > 0)
                {
                    finalImagePath = await SaveFile(imageFile, "images");
                }

                // 获取WriteApiUrl配置
                var writeApiUrl = _configuration["ApiSettings:WriteApiUrl"] ?? "http://localhost:5090/api";
                var url = $"{writeApiUrl}/Defective/Update";

                // 构建请求数据
                var requestData = new UpdateDefectiveRequest
                {
                    Id = defectiveId,
                    DefectiveCode = defectiveCode,
                    DefectiveName = defectiveName,
                    AttachmentPath = finalAttachmentPath ?? "",
                    ImagePath = finalImagePath ?? "",
                    ModifierId = modifierId
                };

                // 发送PUT请求到WriteApiUrl
                var jsonContent = JsonSerializer.Serialize(requestData);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                // 使用HttpMethod.Put创建PUT请求
                var request = new HttpRequestMessage(HttpMethod.Put, url)
                {
                    Content = content
                };

                var response = await _httpClient.SendAsync(request);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var result = JsonSerializer.Deserialize<AddDefectiveResponse>(responseContent, new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });

                    return Json(result);
                }
                else
                {
                    var errorMessage = response.StatusCode == System.Net.HttpStatusCode.Unauthorized 
                        ? "API需要认证，请先登录" 
                        : $"更新失败，状态码: {response.StatusCode}";
                    return Json(new { code = (int)response.StatusCode, msg = errorMessage, data = 0 });
                }
            }
            catch (Exception ex)
            {
                return Json(new { code = 500, msg = $"更新异常: {ex.Message}", data = 0 });
            }
        }

        /// <summary>
        /// 批量删除不良品
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> DeleteBatch([FromBody] DeleteDefectiveRequest request)
        {
            try
            {
                // 验证请求参数
                if (request?.Ids == null || request.Ids.Count == 0)
                {
                    return Json(new { code = 400, msg = "请选择要删除的不良品项", data = 0 });
                }

                // 获取WriteApiUrl配置
                var writeApiUrl = _configuration["ApiSettings:WriteApiUrl"] ?? "http://localhost:5090/api";
                var url = $"{writeApiUrl}/Defective/DeleteBatch";

                // 构建请求数据
                var requestData = new DeleteDefectiveRequest
                {
                    Ids = request.Ids
                };

                // 发送DELETE请求到WriteApiUrl
                var jsonContent = JsonSerializer.Serialize(requestData);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                // 使用HttpMethod.Delete创建DELETE请求
                var httpRequest = new HttpRequestMessage(HttpMethod.Delete, url)
                {
                    Content = content
                };

                var response = await _httpClient.SendAsync(httpRequest);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var result = JsonSerializer.Deserialize<DeleteDefectiveResponse>(responseContent, new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });

                    return Json(result);
                }
                else
                {
                    var errorMessage = response.StatusCode == System.Net.HttpStatusCode.Unauthorized 
                        ? "API需要认证，请先登录" 
                        : $"删除失败，状态码: {response.StatusCode}";
                    return Json(new { code = (int)response.StatusCode, msg = errorMessage, data = 0 });
                }
            }
            catch (Exception ex)
            {
                return Json(new { code = 500, msg = $"删除异常: {ex.Message}", data = 0 });
            }
        }

        /// <summary>
        /// 获取当前登录用户ID
        /// </summary>
        private int GetCurrentUserId()
        {
            // 这里需要根据实际的认证系统来实现
            // 例如从JWT Token、Session或Claims中获取用户ID
            
            // 临时实现：从Session获取用户ID
            var userId = HttpContext.Session.GetString("UserId");
            if (!string.IsNullOrEmpty(userId) && int.TryParse(userId, out int id))
            {
                return id;
            }
            
            // 如果Session中没有，尝试从Claims获取
            var userClaim = User.FindFirst("UserId");
            if (userClaim != null && int.TryParse(userClaim.Value, out int claimId))
            {
                return claimId;
            }
            
            // 默认返回1（开发测试用）
            return 1;
        }

        /// <summary>
        /// 保存上传的文件
        /// </summary>
        private async Task<string> SaveFile(IFormFile file, string folder)
        {
            try
            {
                // 确保上传目录存在
                var uploadPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads", folder);
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }

                // 生成唯一文件名
                var fileName = $"{Guid.NewGuid()}_{Path.GetFileName(file.FileName)}";
                var filePath = Path.Combine(uploadPath, fileName);

                // 保存文件
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // 返回相对路径
                return $"/uploads/{folder}/{fileName}";
            }
            catch (Exception ex)
            {
                // 记录错误日志
                Console.WriteLine($"文件保存失败: {ex.Message}");
                throw new Exception($"文件保存失败: {ex.Message}");
            }
        }
    }
}
